package com.unlcn.erp.hyc.interfaces.backend.service;


import com.unlcn.erp.hyc.interfaces.backend.enums.ExceptionMsgTypeEnum;
import com.unlcn.erp.hyc.interfaces.base.mapper.*;
import com.unlcn.erp.hyc.interfaces.base.model.*;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by zhiche024 on 2017/9/8.
 */
@Service
public class CheckIntermediateServiceImpl implements CheckIntermediateService {

    private static final Logger LOGGER = LoggerFactory.getLogger(CheckIntermediateServiceImpl.class);
    @Autowired
    private SmcitymapMapper smcitymapMapper;
    @Autowired
    private SmcityMapper smcityMapper;
    @Autowired
    private HycExceptionMsgMapper hycExceptionMsgMapper;
    @Autowired
    private SmcustomermapMapper smcustomermapMapper;
    @Autowired
    private SmcustomerMapper smcustomerMapper;
    @Autowired
    private SmmodelsmapMapper smmodelsmapMapper;
    @Autowired
    private SmstyleMapper smstyleMapper;
    @Autowired
    private SmshipmapMapper smshipmapMapper;
    @Autowired
    private SmfleetMapper smfleetMapper;
    @Autowired
    private SmdrivermapMapper smdrivermapMapper;
    @Autowired
    private SmdriverMapper smdriverMapper;
    @Autowired
    private SmvehicleMapper smvehicleMapper;
    @Autowired
    private SmvehiclemapMapper smvehiclemapMapper;
    @Autowired
    private SmgetpointMapper smgetpointMapper;
    @Autowired
    private SmcontractMapper smcontractMapper;
    @Autowired
    private SmcustMapper smcustMapper;
    @Autowired
    private SmwarehouseMapper smwarehouseMapper;
    @Autowired
    private SmruleAutoCustshipnoMapper smruleAutoCustshipnoMapper;
    @Autowired
    private ExecptionDisposeService execptionDisposeService;


    /**
     *  判断城市是否存在
     * @param cityCode 城市编码
     * @param cityName  城市名称
     * @return
     */
    @Override
    public Smcitymap judgeCityMap(String cityCode, String cityName,String orderCode) throws Exception{
        //先查询中间表中是否存在该城市
        SmcitymapExample exampleMap = new SmcitymapExample();
        exampleMap.createCriteria().andNocityidEqualTo(Long.valueOf(cityCode));
        List<Smcitymap> cityMaps = smcitymapMapper.selectByExample(exampleMap);
        Smcitymap smcitymap = new Smcitymap();
        smcitymap.setNocityid(Long.valueOf(cityCode));
        smcitymap.setNocityname(cityName);
        if(CollectionUtils.isNotEmpty(cityMaps)){
            return cityMaps.get(0);
        }else{
            //如果中间表里没有找到，再去查询erp里是否有该城市
            SmcityExample example = new SmcityExample();
            //将城市转换为erp里的数据格式
            String city =  cityName.replace("市","");
            example.createCriteria().andVccitynameEqualTo(city);
            List<Smcity> citys =  smcityMapper.selectByExample(example);
            if(CollectionUtils.isNotEmpty(citys)){
                //erp表中存在，存入到城市中间表中
                Smcity smcity = citys.get(0);
                smcitymap.setVccityid((long)smcity.getIlineid());
                smcitymap.setVccityname(smcity.getVccityname());
                smcitymapMapper.insertCityMapByHYC(smcitymap);
                return smcitymap;
            }else{
                //将城市转换为erp里的数据格式
                city =  cityName.replace("州","");
                SmcityExample cityExample = new SmcityExample();
                cityExample.createCriteria().andVccitynameEqualTo(city);
                List<Smcity> cityList =  smcityMapper.selectByExample(cityExample);
                if(CollectionUtils.isNotEmpty(cityList)){
                    //erp表中存在，存入到城市中间表中
                    Smcity smcity = cityList.get(0);
                    smcitymap.setVccityid((long)smcity.getIlineid());
                    smcitymap.setVccityname(smcity.getVccityname());
                    smcitymapMapper.insertCityMapByHYC(smcitymap);
                    return smcitymap;
                }else {
                    //表明在erp中也没又找到对应的城市
                    //将信息写入到异常信息记录表中
                    execptionDisposeService.saveExecption("ERP中没有找到【"+cityName+"】对应城市",orderCode, ExceptionMsgTypeEnum.MSG_CITYEXCEPTION.getValue());
                }
            }
            return null;
        }
    }

    /**
     * 判断客户中间表是否存在
     * @param customerId
     * @param customerName
     * @return
     * @throws Exception
     */
    @Override
    public Long judgeCustomerpMap(long customerId,String customerName,Long startCityId, Long custId)throws Exception{
        //检查客户中间表
        SmcustomermapExample example = new SmcustomermapExample();
        example.createCriteria().andNocustomeridEqualTo(customerId);
        Smcustomermap smcustomermap = new Smcustomermap();
        smcustomermap.setNocustomerid(customerId);
        smcustomermap.setNocustomername(customerName);
        List<Smcustomermap> customermaps  = smcustomermapMapper.selectByExample(example);
        if(CollectionUtils.isNotEmpty(customermaps)){
            return customermaps.get(0).getVccustomerid();
        }else{//说明在客户中间表中没有找到
            //检查erp中是否有对应的客户
            SmcustomerExample customerExample = new SmcustomerExample();
            customerExample.createCriteria().andVccustomernameEqualTo(customerName);
            List<Smcustomer> customers = smcustomerMapper.selectByExample(customerExample);
            if(CollectionUtils.isNotEmpty(customers)){
                Smcustomer smcustomer = customers.get(0);
                smcustomermap.setVccustomerid((long)smcustomer.getIlineid());
                smcustomermap.setVccustomername(smcustomer.getVccustomername());

            }else{//说明erp中没有找到对应客户
                //在erp增加对应客户
                Long ilineid = smcustomerMapper.getCustomerNextId();
                //获取城市信息
                List<Smcity> smcities = smcityMapper.getCityByIlineid(startCityId);
                if(CollectionUtils.isNotEmpty(smcities)){
                    Smcity smcity = smcities.get(0);

                    //获取客户最大值
                    String maxCustomerNo = smcustomerMapper.getMaxCustomerNo();
                    Smcustomer smcustomer = new Smcustomer();
                    smcustomer.setIlineid(ilineid);
                    smcustomer.setVccustomerno(maxCustomerNo);
                    smcustomer.setVccustomername(customerName);
                    smcustomer.setVccompanyname(customerName);
                    smcustomer.setVccontact("慧运车");
                    smcustomer.setVctel("010-5123221");
                    smcustomer.setVcprovince(smcity.getVcprovince());
                    smcustomer.setVccityname(smcity.getVccityname());
                    smcustomer.setVcuserno("system");
                    smcustomer.setIcustid(custId);
                    smcustomerMapper.insertByHYCCustomer(smcustomer);
                    //新增客户规则
                    SmruleAutoCustshipno smruleAutoCustshipno = new SmruleAutoCustshipno();
                    smruleAutoCustshipno.setIcustomerid(ilineid);
                    smruleAutoCustshipno.setIprintdateType(1);
                    smruleAutoCustshipno.setVcuserno("system");

                    smruleAutoCustshipnoMapper.saveCustShipNo(smruleAutoCustshipno);


                    smcustomermap.setVccustomerid(ilineid);
                    smcustomermap.setVccustomername(customerName);
                }else{
                    LOGGER.error(customerName+"：客户未找到对应城市");
                }

            }
            //将数据保存到客户中间表中
            smcustomermapMapper.saveCustomerMap(smcustomermap);
            return smcustomermap.getVccustomerid();
        }
    }

    /**
     * 判断客户体系是否存在
     * @param customername
     * @return
     * @throws Exception
     */
    @Override
    public Long judgeCust(String customername) throws Exception {
        //1、检查该客户名是否存在对应的客户体系
        SmcustExample example = new SmcustExample();
        example.createCriteria().andVccustomernameEqualTo(customername);
        List<Smcust> smcustList = smcustMapper.selectByExample(example);
        if(CollectionUtils.isNotEmpty(smcustList)){
            Smcust smcust = smcustList.get(0);
            return smcust.getIlineid();
        }else {//说明没有找到对应的客户体系
            Long ilineid = smcustMapper.getNextCustId();
            Smcust smcust = new Smcust();
            smcust.setIlineid(ilineid);
            smcust.setVccustomername(customername);
            smcust.setVccode(customername);
            smcustMapper.saveCustByHYC(smcust);
            return ilineid;
        }
    }

    /**
     * 判断客户合同是否存在
     * @param smcustomerId
     * @return
     * @throws Exception
     */
    @Override
    public Long judgeSmContract(Long smcustomerId) throws Exception{
        //1、先查询该客户获得该客户数据
        List<Smcustomer> smcustomerList = smcustomerMapper.selectByCustomerId(smcustomerId);
        if(CollectionUtils.isNotEmpty(smcustomerList)){
            Smcustomer smcustomer = smcustomerList.get(0);
            //2、在查询该客户手否已经存有合同
            Long contractId = smcontractMapper.getContractIdBycustomerId(smcustomerId);

            if(contractId == null || "".equals(contractId) ){//说明该客户没有找到合同
                //获取主键值
                Long ilineid = smcontractMapper.getNextContractId();
                Smcontract smcontract = new Smcontract();
                smcontract.setIlineid(ilineid);
                smcontract.setVccontractno(smcustomer.getVccustomerno());
                smcontract.setVccontractname(smcustomer.getVccustomername()+"运输");
                smcontract.setItype(0);
                smcontract.setDtdate(new Date());
                smcontract.setDtbegindate(new Date());
                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");//小写的mm表示的是分钟
                try{
                    smcontract.setDtenddate(sdf.parse("2019-12-12"));
                }catch (Exception e){
                    LOGGER.info("时间转换出错");
                }
                smcontract.setIstatus(1);
                smcontract.setIcustomerid(smcustomer.getIlineid());
                smcontract.setIcompanyid(13);
                smcontract.setDtsigndate(new Date());
                smcontract.setBactive(1);
                smcontract.setVcuserno("system");
                smcontractMapper.saveSmContractByHYC(smcontract);
                return ilineid;
            }else{
                return contractId;
            }
        }

        return null;
    }

    /**
     * 判断车型是否存在
     * @param vehicleid
     * @param vehiclename
     * @return
     */
    @Override
    public Long judgeModersMap(long vehicleid, String vehiclename,Long contractId) throws Exception{
        //先去查询中间表
        SmmodelsmapExample example = new SmmodelsmapExample();
        Smmodelsmap smmodelsmap = new Smmodelsmap();
        smmodelsmap.setNomodelsid(vehicleid);
        smmodelsmap.setNomodelsname(vehiclename);
        smmodelsmap.setIcontractid(contractId);
        example.createCriteria().andNomodelsidEqualTo(vehicleid).andNomodelsnameEqualTo(vehiclename).andIcontractidEqualTo(contractId);
        List<Smmodelsmap> modelsMaps = smmodelsmapMapper.selectByExample(example);
        if(CollectionUtils.isNotEmpty(modelsMaps)){
            return modelsMaps.get(0).getVcmodelssid();
        }else{//说明中间表没有该车型
            //查看erp车型表中
            SmstyleExample styleExample = new SmstyleExample();
            styleExample.createCriteria().andVcstylenameEqualTo(vehiclename).andIcontractidEqualTo(contractId).andBactiveEqualTo(1);
            List<Smstyle> smstyles = smstyleMapper.selectByExample(styleExample);
            if(CollectionUtils.isNotEmpty(smstyles)){
                Smstyle smstyle = smstyles.get(0);
                smmodelsmap.setVcmodelssid(smstyle.getIlineid());
                smmodelsmap.setVcmodelsname(smstyle.getVcstylename());
            }else{//说明erp中也没有找到
                Long ilineid = smstyleMapper.getStyleNextId();
                //在erp中新增型号
                Smstyle smstyle = new Smstyle();
                smstyle.setIlineid(ilineid);
                smstyle.setIcontractid(contractId);
                smstyle.setVcstylename(vehiclename);
                smstyle.setItypeid(1);
                smstyle.setVcunit("辆");
                smstyle.setVcuserno("system");

                //将车型信息存入到erp中
                smstyleMapper.saveStyleByHYC(smstyle);

                smmodelsmap.setVcmodelssid(ilineid);
                smmodelsmap.setVcmodelsname(vehiclename);
            }
            //将车型信息存入到中间表中
            smmodelsmapMapper.insertStyleByHYC(smmodelsmap);
            return smmodelsmap.getVcmodelssid();
        }

    }

    /**
     * 判断分供方是否存在
     * @param carrierId
     * @param carrierName
     * @return
     */
    @Override
    public Long judgeShipMap(String carrierId, String carrierName) throws Exception{
        SmshipmapExample smshipmapExample = new SmshipmapExample();
        Smshipmap smshipmap = new Smshipmap();
        smshipmap.setNoshipid(Long.parseLong(carrierId));
        smshipmap.setNoshipname(carrierName);
        smshipmapExample.createCriteria().andNoshipidEqualTo(Long.parseLong(carrierId)).andNoshipnameEqualTo(carrierName);
        List<Smshipmap> smshipmaps = smshipmapMapper.selectByExample(smshipmapExample);
        if(CollectionUtils.isNotEmpty(smshipmaps) ){
            return (long)smshipmaps.get(0).getVcshipid();
        }else{ //中间表没有查找到
            //检查erp分供方表中是否存在
            SmfleetExample smfleetExample = new SmfleetExample();
            smfleetExample.createCriteria().andVcfleetnameEqualTo(carrierName);
            List<Smfleet> smfleets = smfleetMapper.selectByExample(smfleetExample);
            if(CollectionUtils.isNotEmpty(smfleets)){
                Smfleet smfleet = smfleets.get(0);
                smshipmap.setVcshipid((long)smfleet.getIlineid());
                smshipmap.setVcshipname(smfleet.getVcfleetname());

            }else{
                //erp分供方表中没有找到，
                Smfleet smfleet = new Smfleet();
                smfleet.setVcfleetname(carrierName);
                smfleet.setVccontact("HYC");
                smfleet.setIdeptid((short)10);
                smfleetMapper.insertFleetByHYC(smfleet);
                //查询ilineid
                SmfleetExample smfleetExample1 = new SmfleetExample();
                smfleetExample.createCriteria().andVcfleetnameEqualTo(carrierName);
                List<Smfleet> smfleets1 = smfleetMapper.selectByExample(smfleetExample);
                smshipmap.setVcshipid((long)smfleets1.get(0).getIlineid());
                smshipmap.setVcshipname(carrierName);
            }
            smshipmapMapper.insertShipMapByHYC(smshipmap);
            return smshipmap.getVcshipid();
        }
    }

    /**
     * 检查司机是否存在
     * @param driverName
     * @return
     */
    @Override
    public Long judgeDriverMap(String driverName) throws Exception{
        Smdrivermap smdrivermap = new Smdrivermap();
        smdrivermap.setNodrivername(driverName);
        //先检查中间表里是否存在
        SmdrivermapExample example = new SmdrivermapExample();
        example.createCriteria().andNodrivernameEqualTo(driverName);
        List<Smdrivermap> smdrivermapLists =  smdrivermapMapper.selectByExample(example);
        if(CollectionUtils.isNotEmpty(smdrivermapLists)){
            return smdrivermapLists.get(0).getIdriverid();
        }else{//中间表中没有找到
            //检查erp表中是否存在
            SmdriverExample smdriverExample = new SmdriverExample();
            smdriverExample.createCriteria().andVcnameEqualTo(driverName);
            List<Smdriver> smdriverList = smdriverMapper.selectByExample(smdriverExample);
            if(CollectionUtils.isNotEmpty(smdriverList)){
                smdrivermap.setIdriverid((long)smdriverList.get(0).getIlineid());
                smdrivermap.setVcdrivername(smdriverList.get(0).getVcname());
            }else{//erp表中没有找到
                //将司机新增入erp中
                //1、获取ilineid值
                Long ilineid = smdriverMapper.selectNextDriverId();

                Smdriver smdriver = new Smdriver();
                smdriver.setIlineid(ilineid);
                smdriver.setVcname(driverName);
                smdriver.setVctel("1888888888");
                smdriver.setVcmemo("来自慧运车");
                smdriver.setVcmobile("1888888888");
                smdriverMapper.insertDriverByHYC(smdriver);
                smdrivermap.setIdriverid((long)ilineid);
                smdrivermap.setVcdrivername(driverName);
            }
            //将数据存入到中间表中
            smdrivermapMapper.saveDriverByHYC(smdrivermap);
            return smdrivermap.getIdriverid();
        }
    }

    /**
     * 检查车辆是否存在
     * @param vehicleName
     * @return
     */
    @Override
    public Long judgeVehicleMap(String vehicleName,Long shipId,Long driverId) throws Exception{
        Smvehiclemap smvehiclemap = new Smvehiclemap();
        smvehiclemap.setNovehiclename(vehicleName);
        //先检查中间表里是否存在
        SmvehiclemapExample smvehiclemapExample = new SmvehiclemapExample();
        smvehiclemapExample.createCriteria().andNovehiclenameEqualTo(vehicleName);
        List<Smvehiclemap> smvehiclemapList = smvehiclemapMapper.selectByExample(smvehiclemapExample);
        if(CollectionUtils.isNotEmpty(smvehiclemapList)){
            return smvehiclemapList.get(0).getIvehicleid();
        }else{
            //检查erp车辆信息表中是否存在
            Smvehicle smvehicle = smvehicleMapper.selectVehicleByVclicense(vehicleName);
            if(smvehicle != null){
                smvehiclemap.setIvehicleid(smvehicle.getIlineid());
                smvehiclemap.setVcvehiclename(smvehicle.getVclicense());
            }else{//erp表中没有找到
                //将司机新增入erp中
                //1、获取ilineid值
                Long ilineid = smvehicleMapper.selectNextVehicleId();
                Smvehicle smvehicle1 = new Smvehicle();
                smvehicle1.setIlineid(ilineid);
                smvehicle1.setVclicense(vehicleName);
                smvehicle1.setVcvehicleno(String.valueOf(ilineid));
                smvehicle1.setIfleetid(shipId.shortValue());
                smvehicle1.setIdriverid(driverId.shortValue());
                smvehicle1.setVcuserno("system");
                smvehicle1.setVcmemo("慧运车插入");
                smvehicleMapper.saveVehicleByHYC(smvehicle1);

                smvehiclemap.setIvehicleid(ilineid);
                smvehiclemap.setVcvehiclename(vehicleName);
            }
            smvehiclemapMapper.insertVehicleMapByHYC(smvehiclemap);
            return smvehiclemap.getIvehicleid();
        }

    }

    /**
     * 判断提车库是否存在
     * @param customerId   客户ID
     * @param pointName     提车库名称
     * @param province     省份名称
     * @return      提车库ID
     */
    @Override
    public Long judgeGetPointIsExist(Long customerId, String pointName, String province) throws Exception{
        //1、检查该提车库是否存在
        SmgetpointExample example = new SmgetpointExample();
        example.createCriteria().andIcustomeridEqualTo(customerId).andVcpointnameEqualTo(pointName).andBactiveEqualTo(1L);
        List<Smgetpoint> smgetpointList = smgetpointMapper.selectByExample(example);
        if(CollectionUtils.isNotEmpty(smgetpointList)){
            Smgetpoint smgetpoint = smgetpointList.get(0);
            return smgetpoint.getIlineid();
        }else{//说明没有找到提车库
            //2、新增提车库信息
            //2.1、获取主键值
            Long ilineid = smgetpointMapper.getGetPointId();
            Smgetpoint smgetpoint = new Smgetpoint();
            smgetpoint.setIlineid(ilineid);
            smgetpoint.setIcustomerid(customerId);
            smgetpoint.setIcontractid(10L);
            smgetpoint.setIwarehouseid(10L);
            smgetpoint.setVcpointname(pointName);
            smgetpoint.setVccityname(pointName);
            smgetpoint.setVcprovince(province);
            smgetpoint.setVcmemo("用于慧运车体系调度");
            smgetpoint.setVccontact("慧运车");
            smgetpoint.setBactive(1L);
            smgetpointMapper.saveGetPointByHYC(smgetpoint);
            return ilineid;
        }
    }

    /**
     *  判断子合同是否存在
     * @param customerId
     * @param contractId
     * @param startCity
     * @return
     * @throws Exception
     */
    @Override
    public Long judgeSmWarehouse(Long customerId, Long contractId, Smcitymap startCity) throws Exception {
        //检查装车点是否存在ERP中
        SmwarehouseExample example = new SmwarehouseExample();
        example.createCriteria().andIcustomeridEqualTo(customerId).andIcontractidEqualTo(contractId)
                .andVccitynameEqualTo(startCity.getVccityname()).andBactiveEqualTo(1);
        List<Smwarehouse> smwarehouseList = smwarehouseMapper.selectByExample(example);
        if(CollectionUtils.isNotEmpty(smwarehouseList)){
            return smwarehouseList.get(0).getIlineid();
        }else{//说明在erp中没有找到对应的提车点
            String province = "";
            //获取提车点的主键值
            Long ilineid = smwarehouseMapper.getWarehouseNextId();
            //将该提车点存入到ERP中
            Smwarehouse smwarehouse = new Smwarehouse();
            smwarehouse.setIlineid(ilineid);
            smwarehouse.setIcustomerid(customerId);
            smwarehouse.setIcontractid(contractId);
            smwarehouse.setVccityname(startCity.getVccityname());
            smwarehouse.setVcaddress(startCity.getNocityname());
            smwarehouse.setVcwarehousename(startCity.getVccityname());
            SmcityExample smcityExample = new SmcityExample();
            smcityExample.createCriteria().andVccitynameEqualTo(startCity.getVccityname());
            List<Smcity> smcityList = smcityMapper.selectByExample(smcityExample);
            if(CollectionUtils.isNotEmpty(smcityList)){
                province = smcityList.get(0).getVcprovince();
            }else{
                LOGGER.error("提车点未找到对应的城市："+startCity.getVccityname());
            }
            smwarehouse.setVcprovince(province);
            smwarehouse.setVcuserno("system");
            smwarehouse.setVcwarehouseno("H"+String.valueOf(ilineid));
            smwarehouseMapper.saveWarehouse(smwarehouse);
            return ilineid;
        }
    }

    @Override
    public String switchCityName(String noCityName) throws Exception {
        return smcitymapMapper.switchCityName(noCityName);
    }
}
